define(function(require){
    $(function(){
    	/*---------- 流量分片管理——管理员 ----------*/
    	traffic_id = semi.utils.getUrlParam('traffic');
    	
        /* 表格 */
    	var bodyTemplate = ['<tr resource_id="{id}">',
	    	                    '<td class="txtc" start="{start}" end="{end}">{start} 至 {end}</td>',
	    	                    '<td class="txtc">{hours}</td>',
	    	                    '<td class="txtc">{areas}</td>',
	    	                    '<td class="txtc">{cost}</td>',
	    	                    '<td class="txtc">{org}</td>',
		                     	'<td class="txtc">',
		                     		'<a class="ibtn showchart" href="javascript:;" title="查看报表"><span class="glyphicon glyphicon-list-alt"></span></a>',
		                     		'<a class="ibtn editbtn" href="javascript:;" title="修改"><span class="glyphicon glyphicon-pencil"></span></a>',
		                     		'<a class="ibtn delbtn" can_deleted="{deleted}" href="javascript:;" title="删除"><span class="glyphicon glyphicon-remove"></span></a>',
	                     		'</td>',
		                     '</tr>'].join('');
        
        var date = $('[name=reservation]').val().split(' 至 ');
        var grid = Grid.init({
	            holder:'recourseList',
	            bodyTemplate:bodyTemplate,
	            dataSource:'/trp/resource/get_resources/',
	            pageTemplate:semi.grid.pageTemplate,
	            sendOnPageSize: true
	        });
        
        grid.modifyModel(function(data){
        	if(data.hours.length==24){
    			data.hours = '全天';
    		}else{
    			data.hours = semi.utils.shorterNums(data.hours).join(',');
    		}
        	//position_name、position_attrs、width、height、media_name、media_attrs、floor

        	/*if(data.bid_type == 'CPM'){
        		data.floor += '<span style="font-size:12px;">元/千次曝光</span>'
        	}*/
    	});
        //表格数据-是否可删  deleted  1,可删；0，不能删
        grid.onfilled(function(data){
        	grid.data = data;
        	var time = data.time;
        	$('#recourseList,#trafficList').data('time',time);
        	$('#recourseList tbody tr').each(function(){
        		var $tr = $(this), start = $('[start]',$tr).attr('start'), end = $('[end]',$tr).attr('end');
        		if(moment(time).diff(moment(start))<0){//未开始
        			$tr.data('state','0');
        		}else if(moment(end).diff(moment(time))<0){//已结束
        			$tr.data('state','2');
        			$('.editbtn',$tr).addClass('disabled').removeClass('editbtn');
        			$('.delbtn',$tr).addClass('disabled').removeClass('delbtn');
        			$('.createresource',$tr).addClass('disabled').removeClass('createresource');
        		}else{//进行中
        			$tr.data('state','1');
        			$('.editbtn',$tr).addClass('disabled').removeClass('editbtn');
        			$('.delbtn',$tr).addClass('stopbtn').removeClass('delbtn').attr('title','停止').children('span').removeClass('glyphicon-remove').addClass('glyphicon-stop');
        		}
        		if(time==end){//最后一天
        			$('.stopbtn',$tr).addClass('disabled').removeClass('stopbtn');
        		}
        	});
        	
        	$('#recourseList .delbtn').each(function(){
        		var $this = $(this), can_deleted = $this.attr('can_deleted');
        		if(can_deleted=='0'){
        			$this.addClass('disabled').removeClass('delbtn');
        			$this.siblings('.editbtn').addClass('disabled').removeClass('editbtn');
        		}
        	});
        	if(semi.utils.isEmpty($('#trafficList').data('loaded'))){
        		var tdTmpl = ['<td class="txtc">{position_name}</td>',
        		                '<td class="txtc">{position_attrs}</td>',
        		                '<td class="txtc">{width}</td>',
        		                '<td class="txtc">{height}</td>',
        		                '<td class="txtc">{max}</td>',
        		                '<td class="txtc">{media_name}</td>',
        		                '<td class="txtc">{media_attrs}</td>',
        		                '<td class="txtc" start="{start}" end="{end}">{start} 至 {end}</td>',
        		                '<td class="txtc">{bid_type}</td>',
        		                '<td class="txtc">{bid_price}</td>',
        		                '<td class="txtc">{pv}</td>',
        		                '<td class="txtc">{click}</td>',
        		                '<td class="txtc">{shared}</td>',
        		                '<td class="txtc">{floor}</td>',
        		                '<td class="txtc" active="{active}"><div class="btn-group btn-group-sm"><button type="button" class="btn btn-success traffic-open">开</button><button type="button" class="btn btn-default traffic-close">关</button></div></td>',].join('');
        		
        		tdTmpl = tdTmpl.replaceAll('{position_name}', data.position_name)
        					   .replaceAll('{position_attrs}', data.position_attrs)
        					   .replaceAll('{width}', data.width)
        					   .replaceAll('{height}', data.height)
        					   .replaceAll('{max}', data.max)
        					   .replaceAll('{media_name}', data.media_name)
        					   .replaceAll('{media_attrs}', data.media_attrs)
        					   .replaceAll('{start}', data.start)
        					   .replaceAll('{end}', data.end)
        					   .replaceAll('{bid_type}', data.bid_type)
        					   .replaceAll('{bid_price}', data.bid_price)
        					   .replaceAll('{pv}', data.pv)
        					   .replaceAll('{click}', data.click)
        					   .replaceAll('{shared}', data.shared)
        					   .replaceAll('{floor}', data.floor)
        					   .replaceAll('{active}', data.active)
        						
        		$('#trafficList tbody tr').empty().append(tdTmpl);
        		
        		var border = '';
        		$('#trafficList thead th,#trafficList tbody td').each(function(){
        			if($(this).isTag('th')){
        				$(this).css('border-top',border);
        			}else{
        				$(this).css('border-bottom',border);
        			}
        			if(this.scrollWidth > this.clientWidth){
                        $(this).addClass('ellipsis').attr('title', $(this).text());
                    }else{
                    	$(this).removeAttr('title');
                    }
        		});
        		$('#trafficList thead th:first,#trafficList tbody td:first').css('border-left',border);
        		$('#trafficList thead th:last,#trafficList tbody td:last').css('border-right',border);
        		
        		$('#trafficList td[active]').each(function(){
            		var $this = $(this), active = $this.attr('active');
            		if(active=='1'){
            			$('.btn:first',$this).removeClass('btn-default').addClass('btn-success');
            			$('.btn:last',$this).removeClass('btn-danger').addClass('btn-default');
            		}else{
            			$('.btn:first',$this).removeClass('btn-success').addClass('btn-default');
            			$('.btn:last',$this).removeClass('btn-default').addClass('btn-danger');
            		}
            	});
        		
        		if(moment(time).diff(moment(data.start))<0){//未开始
        			$('#trafficList').data('state','0');
        		}else if(moment(data.end).diff(moment(time))<0){//已结束
        			$('#trafficList').data('state','2');
        			$('.createresource').addClass('disabled');
        		}else{//进行中
        			$('#trafficList').data('state','1');
        		}
        		
        		$('#trafficList').data('loaded',true);
        	}
        	$('.ibtn').tooltip();
        });
        
        /* 数据搜索 */
        var filterData = function(pno){
        	var txt = $('.searchbox-ipt').val(),
            	d = $('[name=reservation]').val().split(' 至 '),
            	pageSize = 20;
        	
        	if($('select.page-size').size()>0){
        		pageSize = $('select.page-size').val();
        	}
            grid.send({
            	traffic: traffic_id,
        		search_text: txt,
        		start: d[0],
        		end: d[1],
        		pageSize: pageSize,
        		pageNo: pno || 1
        	});
        };
        filterData();
        
        //按购买周期模糊搜索
        $('input[name=reservation]').daterangepicker({
        	opens: 'left',
            format:'YYYY-MM-DD'
        }, function(start, end, label) {
        	console.log(start.toISOString(), end.toISOString(), label);
        	filterData();
        });
        
        //按名称、属性模糊搜索
        $('.pageheader .searchbox-btn').on('click', function(){
        	filterData();
        });
        $('.pageheader .searchbox-ipt').on('keyup', function(e){
        	if(e.keyCode==semi.keyCode.ENTER){
        		filterData();
        	}
        });
        
        /* 新建流量分片 */
        $(document).on('click', '.createresource', function(){
        	if($(this).hasClass('disabled')){
        		$dialog.alert('该流量已结束，不再提供分片！','warning');
        		return;
        	}
        	require.async('./common/popresource', function($resource){
        		$resource.create({
        			id: traffic_id,
        			start: ($('#trafficList').data('state')==0?$('#trafficList [start]').attr('start'):$('#trafficList').data('time')),
        			end: $('#trafficList [end]').attr('end'),
        			min: ($('#trafficList').data('state')==0?$('#trafficList [start]').attr('start'):$('#trafficList').data('time')),
        			max: $('#trafficList [end]').attr('end'),
        			success: function(){
        				filterData();
        			}
        		});
        	});
        });
        
        /* 修改-dialog */
        $(document).on('click', '.editbtn', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), resource_id = $tr.attr('resource_id'),
        		_start = $('[start]',$tr).attr('start'),
        		_end = $('[end]',$tr).attr('end'),
        		time = $('#trafficList').data('time');
        	
        	require.async('./common/popresource', function($resource){
        		$resource.edit({
        			id: resource_id,
        			start: _start,
        			end: _end,
        			min: ($('#trafficList').data('state')==0?$('#trafficList [start]').attr('start'):$('#trafficList').data('time')),
        			max: $('#trafficList [end]').attr('end'),
        			success:  function(){
        				filterData(semi.utils.gridPage(grid));
        	        }
        		});
        	});
        });
        
        /* 删除-dialog */
        $(document).on('click', '.delbtn,.stopbtn', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), resource_id = $tr.attr('resource_id');
        	require.async('./common/popresource', function($resource){
        		$resource.del({
        			id: resource_id,
        			isdel: $this.hasClass('delbtn'),
        			success: function(){
        				filterData(semi.utils.gridPage(grid));
        			}
        		});
        	});
        });
        
        /* 查看报表-dialog */
        var $popchart = require('./common/popchart');
        $(document).on('click', '.showchart', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), resource_id = $tr.attr('resource_id');
        	$popchart({
            	title: '广告位分片流量报表',
            	btn: $this,
            	dataurl: '/trp/resource/report',
            	type: 'resource',
            	idname: 'resource',
            	idvalue: resource_id
            });
        });
        
        /* 流量开关 */
        $(document).on('click', '.traffic-open,.traffic-close', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), isloading = $tr.data('loading'), active;
        	if(($this.hasClass('traffic-open') && $this.hasClass('btn-success')) || $this.hasClass('traffic-close') && $this.hasClass('btn-danger') || (!semi.utils.isEmpty(isloading) && isloading))return;
        	$tr.data('loading',true);
        	//active:1为开，0为关
        	if($this.hasClass('traffic-open')){
        		active = 1;
        	}else{
        		active = 0;
        	}
        	$ajax.ajax({
        		url: '/trp/traffic/do_on_off',
        		type: 'post',
        		data: {
        			traffic_id: traffic_id,
        			active: active
        		},
        		success: function(data){
        			if(active==1){
        				$this.addClass('btn-success').siblings('.btn').removeClass('btn-danger');
        			}else{
        				$this.addClass('btn-danger').siblings('.btn').removeClass('btn-success');
        			}
        			$tr.data('loading',false);
        		},
        		error: function(){
        			$dialog.alert('流量开关修改失败，请稍后重试！','warning');
        		}
        	});
        });
    });
});